<template>
  <Modal
    v-model:visible="visible"
    :title="title"
    :confirm-loading="confirmLoading"
    :destroyOnClose="true"
    @ok="handlerSubmit"
    @cancel="closeModal"
    okText="确认"
    cancelText="取消"
  >
    <BasicForm @register="registerForm"></BasicForm>
  </Modal>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { sourceSchema } from './data';
import BasicForm from '/@/components/BasicForm/BasicForm.vue';
import { useBasicForm } from '/@/components/BasicForm/hooks/useBasicForm';

import { Modal } from 'ant-design-vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { createDataSource } from '/@/api/system-mgmt/source-mgmt/source';

const visible = ref<boolean>(false);
const emit = defineEmits(['success', 'register']);
const { createMessage } = useMessage();
const title = ref('新增数据源');
const confirmLoading = ref<boolean>(false);
const [registerForm, { validate, resetFields }] = useBasicForm({
  schemas: sourceSchema,
  showActionButtonGroup: false,
  labelWidth: 120,
});

const showModal = async () => {
  visible.value = true;
  resetFields;
};

const closeModal = () => {
  visible.value = false;
};

async function handlerSubmit() {
  const value = await validate();
  confirmLoading.value = true;

  if (!value.isUsed && value.isUsed != 0) {
    value.isUsed = 0;
  }

  const res = await createDataSource(value);
  if (res === '增加数据源信息成功！') {
    createMessage.success(res);
  } else {
    createMessage.error(res);
  }

  closeModal();
  emit('success');
  confirmLoading.value = false;
}

defineExpose({ showModal });
</script>
